﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using YiSha.Entity.SystemManage;
using YiSha.Model.Param.SystemManage;
using YiSha.Model.Result;
using YiSha.Util;
using YiSha.Util.Model;
using YiSha.Data.Repository;
using YiSha.Business.Cache;
using YiSah.Entity.Extension.Systen;
using YiSha.Enums;

namespace YiSha.Service.SystemManage
{
    /// <summary>
    /// 区域服务
    /// </summary>
    public class AreaService : RepositoryFactory
    {
        public AreaCache areaCache { get; set; }

        #region 获取数据
        public async Task<TData<List<AreaEntity>>> GetList(AreaListParam param)
        {
            TData<List<AreaEntity>> obj = new TData<List<AreaEntity>>();
            List<AreaEntity> areaList = await areaCache.GetList();
            if (param != null)
            {
                if (!param.AreaName.IsEmpty())
                {
                    areaList = areaList.Where(t => t.AreaName.Contains(param.AreaName)).ToList();
                }
            }
            obj.Data = areaList;
            return obj;
        }

        public async Task<TData<List<AreaEntity>>> GetPageList(AreaListParam param, Pagination pagination)
        {
            TData<List<AreaEntity>> obj = new TData<List<AreaEntity>>();
            var expression = ExtLinq.True<AreaEntity>();
            if (!param.AreaName.IsEmpty())
            {
                expression = expression.And(a => a.AreaName.Contains(param.AreaName));
            }
            var list = SqlSugarAdapters.GetPager(expression, pagination);
            obj.Data = list.Item2;
            obj.Total = list.Item1;
            return obj;
        }

        public async Task<TData<List<ZtreeInfo>>> GetZtreeAreaList(AreaListParam param)
        {
            var obj = new TData<List<ZtreeInfo>>();
            obj.Data = new List<ZtreeInfo>();
            List<AreaEntity> list = await areaCache.GetList();
            foreach (AreaEntity area in list)
            {
                obj.Data.Add(new ZtreeInfo
                {
                    id = area.AreaCode,
                    pId = area.ParentAreaCode,
                    name = area.AreaName
                });
            }
            return obj;
        }
        /// <summary>
        /// 查询详情
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task<TData<AreaEntity>> GetEntity(string id)
        {
            TData<AreaEntity> obj = new TData<AreaEntity>();
            obj.Data = SqlSugarAdapters.GetEntity<AreaEntity>(s => s.Id == id);
            return obj;
        }

        #endregion

        #region 提交数据
        public async Task<TData<string>> SaveForm(AreaEntity entity)
        {
            TData<string> obj = new TData<string>();
            try
            {
                if (ExistName(entity))
                {
                    obj.MsgCode = MsgCode.Fail;
                    obj.Msg = "当前区域名称已经存在！";
                    return obj;
                }
                entity.Create();
                SqlSugarAdapters.Insert(entity);
                return obj;
            }
            catch (Exception ex)
            {
                obj.MsgCode = MsgCode.Fail;
                obj.Msg = ex.Message;
                return obj;
            }
        }
        private bool ExistName(AreaEntity entity)
        {
            var expression = ExtLinq.True<AreaEntity>();
            expression = expression.And(t => t.Valid);
            if (entity.Id.IsEmpty())
            {
                expression = expression.And(t => t.AreaName == entity.AreaName);
            }
            else
            {
                expression = expression.And(t => t.AreaName == entity.AreaName && t.Id != entity.Id);
            }
            return SqlSugarAdapters.GetList(expression).Count() > 0 ? true : false;
        }
        /// <summary>
        /// 删除数据
        /// </summary>
        /// <param name="ids"></param>
        /// <returns></returns>
        public async Task<TData> DeleteForm(List<string> ids)
        {
            TData result = new TData();
            try
            {
                var info = SqlSugarAdapters.GetList<AreaEntity>(s => ids.Contains(s.Id));
                if (info.Count > 0)
                {
                    SqlSugarAdapters.Delete<AreaEntity>(s => ids.Contains(s.Id));
                }
                else
                {
                    result.MsgCode = MsgCode.Fail;
                    result.Msg = "当前数据不存在";
                }
            }
            catch (Exception ex)
            {
                result.MsgCode = MsgCode.Fail;
                result.Msg = ex.Message;
            }
            return result;
        }
        #endregion

        #region 公有方法
        public void SetAreaParam<T>(T t) where T : BaseAreaParam
        {
            if (t != null)
            {
                BaseAreaParam param = t as BaseAreaParam;
                if (param != null)
                {
                    //if (!string.IsNullOrEmpty(param.AreaId))
                    //{
                    //    string[] areaIdArr = param.AreaId.Split(new string[] { "," }, StringSplitOptions.RemoveEmptyEntries);
                    //    if (areaIdArr.Length >= 1)
                    //    {
                    //        param.ProvinceId = areaIdArr[0].ParseToInt();
                    //    }
                    //    if (areaIdArr.Length >= 2)
                    //    {
                    //        param.CityId = areaIdArr[1].ParseToInt();
                    //    }
                    //    if (areaIdArr.Length >= 3)
                    //    {
                    //        param.CountyId = areaIdArr[2].ParseToInt();
                    //    }
                    //}
                }
            }
        }

        public void SetAreaEntity<T>(T t) where T : BaseAreaEntity
        {
            if (t != null)
            {
                BaseAreaEntity entity = t as BaseAreaEntity;
                if (entity != null)
                {
                    if (!string.IsNullOrEmpty(entity.AreaId))
                    {
                        string[] areaIdArr = entity.AreaId.Split(new string[] { "," }, StringSplitOptions.RemoveEmptyEntries);
                        if (areaIdArr.Length >= 1)
                        {
                            entity.ProvinceId = areaIdArr[0];
                        }
                        else
                        {
                            entity.ProvinceId = "0";
                        }
                        if (areaIdArr.Length >= 2)
                        {
                            entity.CityId = areaIdArr[1];
                        }
                        else
                        {
                            entity.CityId = "0";
                        }
                        if (areaIdArr.Length >= 3)
                        {
                            entity.CountyId = areaIdArr[2];
                        }
                        else
                        {
                            entity.CountyId = "0";
                        }
                    }
                }
            }
        }

        public void SetAreaId<T>(T t) where T : BaseAreaEntity
        {
            if (t != null)
            {
                BaseAreaEntity entity = t as BaseAreaEntity;
                if (entity != null)
                {
                    entity.AreaId = string.Empty;
                    if (!entity.ProvinceId.IsEmpty())
                    {
                        entity.AreaId += entity.ProvinceId.ParseToString() + ",";
                        if (!entity.CityId.IsEmpty())
                        {
                            entity.AreaId += entity.CityId.ParseToString() + ",";
                            if (!entity.CountyId.IsEmpty())
                            {
                                entity.AreaId += entity.CountyId.ParseToString() + ",";
                            }
                        }
                    }
                    entity.AreaId = entity.AreaId.Trim(',');
                }
            }
        }
        #endregion 
    }
}
